package com.zhi.syc.data_applist;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Location;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.zhi.syc.data_applist.logger.ASLogger;
import com.zhi.syc.data_applist.services.ASLocationInfo;
import com.zhi.syc.data_applist.util.ASUtil;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ASGpsManager {
    public Context mContext;

    public String mBorrowId;

    public String mToken;

    public String mUserName;

    public String mAdvertId;

    public String mLongitude;

    public String mLatitude;

    public String mAddress;

    public int mGetCount = 1;

    private String mUtf8Char = "UTF-8";

    private static final ASGpsManager instance = new ASGpsManager();

    public static ASGpsManager getInstance() {
        return instance;
    }

    public ASGpsManager() {
    }

    public ASGpsManager init(Context paramContext) {
        ASBuilder.PCK_CONTEXT = paramContext;
        this.mContext = paramContext;
        return this;
    }

    public ASGpsManager setToken(String token) {
        this.mToken = ASUtil.safeString(token);
        return this;
    }

    public ASGpsManager setBorrowId(String borrowId) {
        this.mBorrowId = ASUtil.safeString(borrowId);
        return this;
    }

    public void sycData() {

        if (this.mContext == null) return;
        if (ASBuilder.RESULT_LOCATION) return;

        ASBuilder.resetResult(ASBuilder.TYPE_LOCATION);

        try {
            boolean canLocation = ASLocationInfo.init(this.mContext);
            if (canLocation) {
                ASLocationInfo.getLocationInfo(locationInfoBean -> {
                    if (locationInfoBean != null) {
                        //判断是否有效
                        if ((TextUtils.isEmpty(locationInfoBean.getLongitude())) ||
                                (TextUtils.isEmpty(locationInfoBean.getLatitude()))) {
                            if (mGetCount > 3) {
                                postResutl(ASBuilder.TYPE_LOCATION, false, 1003, "获取定位出错-次数超限", "");
                                return;
                            }
                            mGetCount += 1;
                            postResutl(ASBuilder.TYPE_LOCATION, false, 1003, "获取定位出错-次数" + mGetCount, "");
                            sycData();
                            return;
                        }

                        locationInfoBean.setBorrowId(mBorrowId);
                        locationInfoBean.setProduct(ASBuilder.KEY_PRODUCT);
                        locationInfoBean.setAppId(ASBuilder.APPID);

                        //保存数据
                        mLatitude = locationInfoBean.getLatitude();
                        mLongitude = locationInfoBean.getLongitude();
                        mAddress = locationInfoBean.getDetail();

                        String result = new Gson().toJson(locationInfoBean).trim();
                        //ASLogger.d(getClass().getSimpleName(), "run: " + TYPE_LOCATION + "：" + result);
                        new Thread(new LocationRunable(result)).start();
                    } else {
                        postResutl(ASBuilder.TYPE_LOCATION, false, 1003, "获取定位出错", "");
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        new Thread(new LocationCheckRunable()).start();
    }

    public void sycDataByConditions(String token, String borrowId, String conditions) {
        if (TextUtils.isEmpty(conditions)) return;
        if (conditions.contains(ASBuilder.TYPE_LOCATION)) {
            sycData();
        }
    }

    public void sycDataByConditionsV2() {
        sycData();
    }

    public final String getReceiver() {
        String receiver = ASBuilder.AS_RECEIVER;
        try {
            receiver = (this.mContext.getPackageName() + ASBuilder.AS_RECEIVER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return receiver;
    }

    public final void postResutl(String type, boolean success, int resultCode, String resultMsg, String data) {
        try {
            if (success) {
                if (ASBuilder.REMOVE_LOCATION_CALLBACK_WHEN_FINISH) {
                    ASLocationInfo.getInstance().removeUpdateMonitor();
                }
            }

            String state = (success ? "YES" : "NO");
            Intent intent = new Intent();
            intent.setAction(ASBuilder.AS_ACTION);
            intent.putExtra("SyncedData", data);
            intent.putExtra("SyncedMsg", resultMsg);
            intent.putExtra("SyncedState", state);
            intent.putExtra("SyncedType", type);
            intent.putExtra("SyncedCode", String.valueOf(resultCode));
            intent.putExtra("SyncedBorrowId", ASUtil.safeString(this.mBorrowId));
            intent.setPackage(this.mContext.getPackageName());
            intent.setComponent(new ComponentName(this.mContext.getPackageName(), getReceiver()));
            this.mContext.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public final void postData(String url, String type, String body) {
        String dirUrl = ASBuilder.B_SERVER_HOST + url;
        ASLogger.d(getClass().getSimpleName(), "postUrl: " + dirUrl);

        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = ((HttpURLConnection) new URL(dirUrl).openConnection());
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Content-Length", (body.getBytes()).length + "");
            httpURLConnection.setReadTimeout(180000);
            httpURLConnection.setConnectTimeout(120000);
            httpURLConnection.getOutputStream().write(body.getBytes());
            httpURLConnection.getOutputStream().flush();
            httpURLConnection.getOutputStream().close();

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                InputStream inputStream = httpURLConnection.getInputStream();
                byte[] arrayOfByte = new byte[1024];
                int len;
                while ((len = inputStream.read(arrayOfByte)) != -1) {
                    byteArrayOutputStream.write(arrayOfByte, 0, len);
                }

                String result = new String(byteArrayOutputStream.toByteArray(), mUtf8Char);
                JSONObject resultObject = new JSONObject(result);
                byteArrayOutputStream.close();
                //ASLogger.d(getClass().getSimpleName(), "postData: " + resultObject);

                String msg = resultObject.getString("msg");
                String codeStr = resultObject.getString("code");
                int code = Integer.parseInt(codeStr);
                if (code == 200 || code == 0) {
                    postResutl(type, true, code, msg, body);
                    ASLogger.d(getClass().getSimpleName(), "post success!");
                } else {
                    postResutl(type, false, code, msg, body);
                    ASLogger.d(getClass().getSimpleName(), "post fail!");
                }
            } else {
                postResutl(type, false, httpURLConnection.getResponseCode(), httpURLConnection.getResponseMessage(), body);
            }

        } catch (Exception e) {
            e.printStackTrace();
            postResutl(type, false, -1, e.getMessage(), body);
        } finally {
            if (httpURLConnection != null) {
                try {
                    //主动关闭inputStream, 这里不需要进行判空操作
                    httpURLConnection.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                httpURLConnection.disconnect();
            }
        }
    }

    class LocationRunable implements Runnable {
        private String mResult;

        public LocationRunable(String result) {
            this.mResult = result;
        }

        @Override
        public void run() {
            try {
                if (mResult != null) {
                    //ASLogger.d(getClass().getSimpleName(), "run: " + TYPE_LOCATION + "：" + mResult);
                    if (ASBuilder.B_IS_MOCK) {
                        postResutl(ASBuilder.TYPE_LOCATION, true, 0, "success", mResult);
                        return;
                    }
                    postData(ASBuilder.PATH_LOCATION, ASBuilder.TYPE_LOCATION, mResult);
                } else {
                    postResutl(ASBuilder.TYPE_LOCATION, false, 1003, "获取定位出错", "");
                }
            } catch (Exception e) {
                postResutl(ASBuilder.TYPE_LOCATION, false, 1003, "获取定位出错", "");
            }
        }
    }

    class LocationCheckRunable implements Runnable {
        @Override
        public void run() {
            try {
                boolean canLocation = ASLocationInfo.init(mContext);
                if (canLocation) {
                    ASLocationInfo.getLocationInfo(locationInfoBean -> {
                        if (locationInfoBean != null) {
                            //判断是否有效
                            if ((TextUtils.isEmpty(locationInfoBean.getLongitude())) ||
                                    (TextUtils.isEmpty(locationInfoBean.getLatitude()))) {
                                if (mGetCount > 3) {
                                    postResutl(ASBuilder.TYPE_LOCATION, false, 1003, "获取定位出错-次数超限", "");
                                    return;
                                }
                                mGetCount += 1;
                                postResutl(ASBuilder.TYPE_LOCATION, false, 1003, "获取定位出错-次数" + mGetCount, "");
                                sycData();
                                return;
                            }
                            locationInfoBean.setProduct(ASBuilder.KEY_PRODUCT);
                            locationInfoBean.setBorrowId(mBorrowId);
                            locationInfoBean.setAppId(ASBuilder.APPID);
                            String result = new Gson().toJson(locationInfoBean).trim();
                            //ASLogger.d(getClass().getSimpleName(), "run: " + TYPE_LOCATION + "：" + result);
                            new Thread(new LocationRunable(result)).start();
                        } else {
                            postResutl(ASBuilder.TYPE_LOCATION, false, 1003, "获取定位出错", "");
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Address getAccuracyAddress(Context context, Location location) {
        return ASLocationInfo.getInstance().getAccuracyAddress(context, location);
    }
}
